﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using STP.Models;
using System.IO;

namespace STP.Account
{
    public partial class ProductInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] == null || Request.QueryString["id"].Length < 1)
            {
                Response.Redirect("~/merchandise/index");
                return;
            }
            DB db = new DB();
            //获取商品id
            string pid=Request.QueryString["id"].ToString().Trim();
            //获取用户的id
            string sql = "select id from users where name='" + Session["user"] + "'";
            SqlDataReader dr = db.ExceRead(sql);
            string userid = "";
            if (dr.Read()) userid = dr["id"].ToString().Trim();
            dr.Close();
            //获取商品所属用户id
            string puid = "";
            sql = "select uid from products where id='" + pid + "'";
            dr = db.ExceRead(sql);
            if (dr.Read()) puid = dr["uid"].ToString().Trim();
            dr.Close();
            //如果用户id不是商品持有者id则跳出
            if(userid!=puid)
            {
                Response.Redirect("~/merchandise/index");
            }
            //获取和显示商品基本信息
            sql = "exec selectProductById '" + pid + "'";
            dr = db.ExceRead(sql);
            if (dr.Read())
            {
                if(!IsPostBack)
                {
                    Name.Text = dr["name"].ToString().Trim();
                    Price.Text = dr["price"].ToString().Trim();
                    Image.ImageUrl = dr["path"].ToString().Trim();
                    Content.Text = dr["content"].ToString().Trim();
                }
                dr.Close();
            }
            else
            {
                Response.Redirect("~/index.aspx");
                return;
            }
            //展示标签
            string taglist = "";
            dr = db.ExceRead("exec selectTagsByProductId '" + pid + "'");
            while(dr.Read())
            {
                taglist += dr["name"]+",";
            }
            dr.Close();
            if (taglist.Length > 0) taglist = taglist.Substring(0, taglist.Length - 1);
            if (!IsPostBack)Tags.Text = taglist;
            //展示用户出价列表
            sql = "select quotes.uid,quotes.price,users.nickname from quotes,users where users.id=quotes.uid and pid='" + Request.QueryString["id"] + "' order by quotes.price desc";
            dr = db.ExceRead(sql);
            TableRow trow = new TableRow();
            TableCell tcell1 = new TableCell();
            TableCell tcell2 = new TableCell();
            Label tl1 = new Label();
            tl1.Text = "出价";
            tl1.Font.Bold = true;
            tcell1.Controls.Add(tl1);
            Label tl2 = new Label();
            tl2.Text = "用户";
            tl2.Font.Bold = true;
            tcell2.Controls.Add(tl2);
            trow.Cells.Add(tcell1);
            trow.Cells.Add(tcell2);
            Quotes.Rows.Add(trow);
            while (dr.Read())
            {
                TableRow row = new TableRow();
                TableCell cell1 = new TableCell();
                TableCell cell2 = new TableCell();
                Label price = new Label();
                price.Text = dr["price"].ToString().Trim();
                cell1.Controls.Add(price);
                HyperLink username = new HyperLink();
                username.Text = dr["nickname"].ToString().Trim();
                username.NavigateUrl = "~/Product/Userinfo?id=" + dr["uid"];
                cell2.Controls.Add(username);
                row.Cells.Add(cell1);
                row.Cells.Add(cell2);
                Quotes.Rows.Add(row);
            }
            dr.Close();
        }

        protected void Unnamed8_Click(object sender, EventArgs e)
        {
            DB db = new DB();
            string pid=Request.QueryString["id"].ToString().Trim();
            db.ExceSql("delete from products where id='" + pid + "'");
            db.ExceSql("delete from products_tags where pid='" + pid + "'");
            db.ExceSql("delete from products_images where pid='" + pid + "'");
            Response.Redirect("~/merchandise/index");
        }

        protected void Unnamed7_Click(object sender, EventArgs e)
        {
            DB db = new DB();
            Boolean fileOk;
            string name = Name.Text;
            string content = Content.Text;
            string price = Price.Text;
            string tags = Tags.Text;
            string pid=Request.QueryString["id"].ToString().Trim();
            string sql = "update products set name='" + name + "',content='" + content + "',price='" + price + "',time=getdate() where id='" + pid + "'";
            db.ExceSql(sql);
            sql = "exec deleteTagsByProductId '" + pid + "'";
            db.ExceSql(sql);
            string[] taglist = tags.Split(',');
            foreach(string tag in taglist)
            {
                if(tag.Length>0)
                {
                    db.ExceSql("exec insertTagForProduct '" + pid + "','" + tag + "'");
                }
            }
            if (picUpload.HasFile)//验证是否包含文件
            {
                string mappath = "";
                string virpath = "";
                //取得文件的扩展名,并转换成小写
                string fileExtension = Path.GetExtension(picUpload.FileName).ToLower();
                //验证上传文件是否图片格式
                fileOk = IsImage(fileExtension);
                if (fileOk)
                {
                    //对上传文件的大小进行检测，限定文件最大不超过8M
                    if (picUpload.PostedFile.ContentLength < 8192000)
                    {
                        string filepath = "/img/";
                        if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就创建file文件夹
                        {
                            Directory.CreateDirectory(Server.MapPath(filepath));
                        }
                        virpath = filepath + "productimg_" + pid + fileExtension;//这是存到服务器上的虚拟路径
                        mappath = Server.MapPath(virpath);//转换成服务器上的物理路径
                        picUpload.PostedFile.SaveAs(mappath);//保存图片
                        //清空提示
                        picLabel.Text = "";
                        sql = "exec insertImageForProduct '" + pid + "','" + virpath + "'";
                        db.ExceSql(sql);
                    }
                    else
                    {
                        picLabel.Text = "文件大小超出8M！请重新选择！";
                    }
                }
                else
                {
                    picLabel.Text = "要上传的文件类型不对！请重新选择！";
                }
            }
            
            Response.Redirect("~/merchandise/index.aspx");
        }
        public bool IsImage(string str)
        {
            bool isimage = false;
            string thestr = str.ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (thestr == allowExtension[i])
                {
                    isimage = true;
                    break;
                }
            }
            return isimage;
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/index.aspx");
        }
    }
}